package ua.edu.nuos.jeetraining2012.automator.services.bl.common.services.message;

import ua.edu.nuos.jeetraining2012.automator.core.vo.message.Message;
import ua.edu.nuos.jeetraining2012.automator.core.vo.message.MessageDestination;
import ua.edu.nuos.jeetraining2012.automator.core.vo.message.MessageSource;

import java.util.logging.Logger;

/**
 * @author Timur Yarosh
 *         Date: 04.06.13
 *         Time: 0:29
 */
public abstract class AbstractMessageService implements IMessageService {
    protected Logger logger;
    protected abstract boolean isAuthorized();
    protected abstract void authorize();
    protected abstract void executeSendMessage(Message message, MessageDestination destination);
    protected abstract Message executeReceiveMessage(MessageSource source);

    protected AbstractMessageService() {
        logger = Logger.getLogger(AbstractMessageService.class.getName());
    }

    @Override
    public void sendMessage(Message message, MessageDestination destination) {
        checkAuthorization();
        executeSendMessage(message, destination);
    }

    @Override
    public Message receiveMessage(MessageSource source) {
        checkAuthorization();
        return executeReceiveMessage(source);
    }

    /**
     * Authorize user if not authorized
     */
    private void checkAuthorization() {
        if (!isAuthorized()) {
            authorize();
        }
    }
}
